<template>
  <n-form
    ref="formRef"
    :model="model"
    :rules="rulesCode"
    size="large"
    :show-label="false"
  >
    <n-form-item ref="formPhoneRef" path="phone">
      <n-input v-model:value="model.phone" placeholder="请输入手机号" />
    </n-form-item>
    <n-form-item ref="formCaptchaRef" path="imgCode">
      <n-input v-model:value="model.imgCode" placeholder="请输入图形验证码" />
      <n-image
        class="w-170 h-38 rd-5 ml-10 cursor-pointer"
        :src="captcha.image"
        preview-disabled
        @click="getCaptcha"
      />
    </n-form-item>
    <n-form-item path="code">
      <div f-y-c w-full>
        <n-input v-model:value="model.code" placeholder="请输入验证码" />
        <div w-18></div>
        <n-button
          size="large"
          :disabled="isCounting"
          :loading="smsLoading"
          @click="handleSmsCode"
        >
          {{ label }}
        </n-button>
      </div>
    </n-form-item>

    <n-space :vertical="true" :size="18">
      <n-button
        type="primary"
        size="large"
        round
        block
        :loading="loading"
        @click="handleSubmit"
      >
        确认
      </n-button>
      <n-button size="large" block round @click="router.back"> 返回 </n-button>
    </n-space>
  </n-form>
</template>

<script setup lang="ts">
import type { FormInst } from "naive-ui";
import { useLoadingFunc, useSmsCode } from "@/hooks";
import { rulesCode } from "../common";
import { authApi } from "@/api";

const router = useRouter();
const { label, isCounting, loading: smsLoading, getSmsCode } = useSmsCode();

const formRef = ref<HTMLElement & FormInst>();
const formPhoneRef = ref<HTMLElement & FormInst>();
const formCaptchaRef = ref<HTMLElement & FormInst>();
const captcha = ref({
  image: "", // base64图片
  key: "",
  code: "",
});
const model = ref({
  phone: "",
  code: "",
  imgCode: "",
});
watch(
  () => model.value.imgCode,
  (newVal) => {
    captcha.value.code = newVal;
  },
  { immediate: true }
);

const handleSmsCode = async () => {
  // 验证手机号
  await formPhoneRef.value?.validate();
  // 验证图形验证码
  await formCaptchaRef.value?.validate();
  if (await validCaptcha()) {
    getSmsCode(model.value.phone);
  } else {
    getCaptcha();
  }
};

const getCaptcha = async () => {
  const { data } = await authApi.captcha();
  captcha.value.image = data.captchaImg;
  captcha.value.key = data.key;
};

const validCaptcha = async () => {
  await authApi.validCaptcha(captcha.value);
  return true;
};

const { loading, func: handleSubmit } = useLoadingFunc(async () => {
  await formRef.value?.validate();
  window.$message?.success("验证成功");
});

onMounted(() => {
  getCaptcha();
});
</script>
